'use client';

import { useEffect, useRef, useState } from 'react';
import {
  Dialog,
  DialogPanel,
  Disclosure,
  DisclosureButton,
  DisclosurePanel,
  Popover,
  PopoverButton,
  PopoverGroup,
  PopoverPanel,
} from '@headlessui/react';
import Link from 'next/link';
import {
  ArrowPathIcon,
  Bars3Icon,
  ChartPieIcon,
  CursorArrowRaysIcon,
  FingerPrintIcon,
  SquaresPlusIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline';
import { PhoneIcon, PlayCircleIcon } from '@heroicons/react/20/solid';

import { usePathname } from 'next/navigation';
import { useMemoizedFn, useSize } from 'ahooks';
import { fira_sans } from './fonts';

const products = [
  {
    name: 'Analytics',
    description: 'Get a better understanding of your traffic',
    href: '#',
    icon: ChartPieIcon,
  },
  {
    name: 'Engagement',
    description: 'Speak directly to your customers',
    href: '#',
    icon: CursorArrowRaysIcon,
  },
  {
    name: 'Security',
    description: 'Your customers’ data will be safe and secure',
    href: '#',
    icon: FingerPrintIcon,
  },
  {
    name: 'Integrations',
    description: 'Connect with third-party tools',
    href: '#',
    icon: SquaresPlusIcon,
  },
  {
    name: 'Automations',
    description: 'Build strategic funnels that will convert',
    href: '#',
    icon: ArrowPathIcon,
  },
];
const callsToAction = [
  { name: 'Watch demo', href: '#', icon: PlayCircleIcon },
  { name: 'Contact sales', href: '#', icon: PhoneIcon },
];

const navList = [
  {
    title: 'HOME',
    index: 1,
    code: '/#home',
    icon: null,
    innerStyle: undefined,
  },
  {
    title: 'PRODUCTS',
    index: 2,
    code: '/#products',
    icon: null,
    innerStyle: undefined,
  },
  {
    title: 'ABOUT',
    index: 3,
    code: '/about',
    icon: null,
    innerStyle: undefined,
  },
  // {
  //   title: 'CONSULTING',
  //   index: 4,
  //   code: '/consulting',
  //   icon: null,
  //   innerStyle: undefined,
  // },
];

export default function Header() {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const navCotRef: { current: HTMLElement | any } = useRef(null);
  const navSize = useSize(navCotRef);
  const pathname = usePathname();
  const [currentHash, setCurrentHash] = useState<string | undefined>();

  const [activeIndex, setActiveIndex] = useState(1);

  const calcDomPos = useMemoizedFn(() => {
    const navDom = navCotRef.current.querySelector(
      `[data-group]>a:nth-child(${activeIndex})`
    );
    const navGroup = navCotRef.current.querySelector(`[data-group]`);
    const navBar = navCotRef.current.querySelector(`[data-nav-bar]`);
    if (!navDom || !navBar) return;
    const groupSize = navGroup.getBoundingClientRect();
    const size = navDom.getBoundingClientRect();
    navBar.style.left = `${size.left - groupSize.left}px`;
    navBar.style.width = `${size.width}px`;
  });

  useEffect(() => {
    calcDomPos();
  }, [navSize, activeIndex, calcDomPos]);

  useEffect(() => {
    const currentPath = ['', '/', undefined, null].includes(currentHash)
      ? 'home'
      : currentHash;
    const curIndex = navList.findIndex(
      item => item.code.indexOf(currentPath as string) !== -1
    );

    setActiveIndex(curIndex > -1 ? curIndex + 1 : -1);
  }, [currentHash]);

  useEffect(() => {
    setCurrentHash(window.location.href.match(/[^\/#]+$/)?.[0]);
  }, [pathname]);

  return (
    <header className="sticky top-0 z-50 bg-white/80 backdrop-blur-xs">
      <div
        className={'relative w-full border-b-1 border-[#E8EFF6]'}
        ref={navCotRef}
      >
        <nav
          aria-label="Global"
          className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4"
        >
          <div className="flex lg:flex-1">
            <a href="#" className="-m-1.5 p-1.5">
              <span className="sr-only">Your Company</span>
              <div
                className={
                  'h-[20px] w-[152px] bg-[url(/Matrixfactors@2x.png)] bg-contain bg-center bg-no-repeat text-gray-900'
                }
              />
            </a>
          </div>
          <div className="flex lg:hidden">
            <button
              type="button"
              onClick={() => setMobileMenuOpen(true)}
              className="-m-2.5 inline-flex items-center justify-center rounded-md p-2.5 text-gray-700"
            >
              <span className="sr-only">Open main menu</span>
              <Bars3Icon aria-hidden="true" className="size-6" />
            </button>
          </div>
          <PopoverGroup
            data-group
            className="relative hidden justify-end self-stretch lg:flex lg:gap-x-12"
          >
            {/*<Popover className="relative inline-flex items-center px-4">*/}
            {/*  <PopoverButton className="flex items-center gap-x-1 text-sm/6 font-semibold text-gray-900">*/}
            {/*    Product*/}
            {/*    <ChevronDownIcon*/}
            {/*      aria-hidden="true"*/}
            {/*      className="size-5 flex-none text-gray-400"*/}
            {/*    />*/}
            {/*  </PopoverButton>*/}

            {/*  <PopoverPanel*/}
            {/*    transition*/}
            {/*    className="absolute top-full -left-8 z-10 mt-3 w-screen max-w-md overflow-hidden rounded-3xl bg-white shadow-lg ring-1 ring-gray-900/5 transition data-closed:translate-y-1 data-closed:opacity-0 data-enter:duration-200 data-enter:ease-out data-leave:duration-150 data-leave:ease-in"*/}
            {/*  >*/}
            {/*    <div className="p-4">*/}
            {/*      {products.map(item => (*/}
            {/*        <div*/}
            {/*          key={item.name}*/}
            {/*          className="group relative flex items-center gap-x-6 rounded-lg p-4 text-sm/6 hover:bg-gray-50"*/}
            {/*        >*/}
            {/*          <div className="flex size-11 flex-none items-center justify-center rounded-lg bg-gray-50 group-hover:bg-white">*/}
            {/*            <item.icon*/}
            {/*              aria-hidden="true"*/}
            {/*              className="size-6 text-gray-600 group-hover:text-indigo-600"*/}
            {/*            />*/}
            {/*          </div>*/}
            {/*          <div className="flex-auto">*/}
            {/*            <a*/}
            {/*              href={item.href}*/}
            {/*              className="block font-semibold text-gray-900"*/}
            {/*            >*/}
            {/*              {item.name}*/}
            {/*              <span className="absolute inset-0" />*/}
            {/*            </a>*/}
            {/*            <p className="mt-1 text-gray-600">{item.description}</p>*/}
            {/*          </div>*/}
            {/*        </div>*/}
            {/*      ))}*/}
            {/*    </div>*/}
            {/*    <div className="grid grid-cols-2 divide-x divide-gray-900/5 bg-gray-50">*/}
            {/*      {callsToAction.map(item => (*/}
            {/*        <a*/}
            {/*          key={item.name}*/}
            {/*          href={item.href}*/}
            {/*          className="flex items-center justify-center gap-x-2.5 p-3 text-sm/6 font-semibold text-gray-900 hover:bg-gray-100"*/}
            {/*        >*/}
            {/*          <item.icon*/}
            {/*            aria-hidden="true"*/}
            {/*            className="size-5 flex-none text-gray-400"*/}
            {/*          />*/}
            {/*          {item.name}*/}
            {/*        </a>*/}
            {/*      ))}*/}
            {/*    </div>*/}
            {/*  </PopoverPanel>*/}
            {/*</Popover>*/}
            {navList.map((nav, index) => {
              const isActive = nav.index === activeIndex;
              const textColor = isActive ? 'text-[#222]' : 'text-[#68727E]';
              return (
                <Link
                  key={nav.code}
                  onClick={() => {
                    setActiveIndex(index + 1);
                  }}
                  href={nav.code}
                  className={`transition-m-2.5 inline-flex items-center px-4 text-[16px] font-semibold ${textColor} ${fira_sans.className} hover:text-[#222]`}
                >
                  {nav.title}
                </Link>
              );
            })}

            <span
              data-nav-bar
              className={`absolute bottom-0 hidden h-[2px] bg-[#0686FF] transition-all duration-300 ease-in-out lg:inline-flex ${activeIndex === -1 ? '!hidden' : ''}`}
            ></span>
          </PopoverGroup>
          {/*<div className="hidden lg:flex lg:flex-1 lg:justify-end">*/}
          {/*  <a href="#" className="text-sm/6 font-semibold text-gray-900">*/}
          {/*    Log in <span aria-hidden="true">&rarr;</span>*/}
          {/*  </a>*/}
          {/*</div>*/}
        </nav>
      </div>

      <Dialog
        open={mobileMenuOpen}
        onClose={setMobileMenuOpen}
        className="lg:hidden"
      >
        <div className="fixed inset-0 z-10" />
        <DialogPanel className="fixed inset-y-0 right-0 z-10 w-full overflow-y-auto bg-white px-6 py-6 sm:max-w-sm sm:ring-1 sm:ring-gray-900/10">
          <div className="flex items-center justify-between">
            <a href="#" className="-m-1.5 p-1.5">
              <span className="sr-only">Your Company</span>
              <img
                alt=""
                src="https://tailwindcss.com/plus-assets/img/logos/mark.svg?color=indigo&shade=600"
                className="h-8 w-auto"
              />
            </a>
            <button
              type="button"
              onClick={() => setMobileMenuOpen(false)}
              className="-m-2.5 rounded-md p-2.5 text-gray-700"
            >
              <span className="sr-only">Close menu</span>
              <XMarkIcon aria-hidden="true" className="size-6" />
            </button>
          </div>
          <div className="mt-6 flow-root">
            <div className="-my-6 divide-y divide-gray-500/10">
              <div className="space-y-2 py-6">
                {/*<Disclosure as="div" className="-mx-3">*/}
                {/*  <DisclosureButton className="group flex w-full items-center justify-between rounded-lg py-2 pr-3.5 pl-3 text-base/7 font-semibold text-gray-900 hover:bg-gray-50">*/}
                {/*    Product*/}
                {/*    <ChevronDownIcon*/}
                {/*      aria-hidden="true"*/}
                {/*      className="size-5 flex-none group-data-open:rotate-180"*/}
                {/*    />*/}
                {/*  </DisclosureButton>*/}
                {/*  <DisclosurePanel className="mt-2 space-y-2">*/}
                {/*    {[...products, ...callsToAction].map(item => (*/}
                {/*      <DisclosureButton*/}
                {/*        key={item.name}*/}
                {/*        as="a"*/}
                {/*        href={item.href}*/}
                {/*        className="block rounded-lg py-2 pr-3 pl-6 text-sm/7 font-semibold text-gray-900 hover:bg-gray-50"*/}
                {/*      >*/}
                {/*        {item.name}*/}
                {/*      </DisclosureButton>*/}
                {/*    ))}*/}
                {/*  </DisclosurePanel>*/}
                {/*</Disclosure>*/}

                {navList.map((nav, index) => {
                  return (
                    <Link
                      key={index}
                      href={nav.code}
                      onClick={() => setMobileMenuOpen(false)}
                      className={`-mx-3 block rounded-lg px-3 py-2 text-base/7 font-semibold text-gray-900 hover:bg-gray-50`}
                    >
                      {nav.title}
                    </Link>
                  );
                })}
              </div>
            </div>
          </div>
        </DialogPanel>
      </Dialog>
    </header>
  );
}
